package io.coderyeah.ymcc.service.impl;

import cn.hutool.core.lang.Validator;
import cn.hutool.core.util.RandomUtil;
import com.google.code.kaptcha.Producer;
import io.coderyeah.ymcc.constant.RedisConstants;
import io.coderyeah.ymcc.constant.YmccConstants;
import io.coderyeah.ymcc.domain.BlackList;
import io.coderyeah.ymcc.domain.MessageSms;
import io.coderyeah.ymcc.dto.RegisterDTO;
import io.coderyeah.ymcc.enums.YmccSystemError;
import io.coderyeah.ymcc.exception.BusinessException;
import io.coderyeah.ymcc.mapper.MessageSmsMapper;
import io.coderyeah.ymcc.property.SMSVerifyCodeProperties;
import io.coderyeah.ymcc.result.JSONResult;
import io.coderyeah.ymcc.service.IVerifyCodeService;
import io.coderyeah.ymcc.util.Base64;
import io.coderyeah.ymcc.util.RedisCache;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.FastByteArrayOutputStream;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author lqs
 * @date 2022/10/20 11:12
 */
@Service
@Slf4j
public class VerifyCodeServiceImpl implements IVerifyCodeService {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private SMSVerifyCodeProperties codeProperties;
    @Autowired
    private MessageSmsMapper smsMapper;

    @Value("${captchaType}")
    private String captchaType;

    @Resource(name = "captchaProducer")
    private Producer captchaProducer;

    @Resource(name = "captchaProducerMath")
    private Producer captchaProducerMath;

    @Autowired
    private RedisCache redisCache;

    public JSONResult sendSmsCode(RegisterDTO dto) {
        if (!Validator.isMobile(dto.getMobile())) {// 判断手机号是否合法
            throw new BusinessException(YmccSystemError.PHONE_PARAM_ERROR);
        }
        Object imageCodeValue = redisTemplate.opsForValue().get(dto.getImageCodeKey());
        if (imageCodeValue == null) {
            throw new BusinessException(YmccSystemError.IMAGE_CODE_EXPIRED);
        }
        if (!imageCodeValue.equals(dto.getImageCode())) {
            // 图形验证码错误
            throw new BusinessException(YmccSystemError.IMAGE_CODE_ERROR);
        }

        // 判断是否拉黑
        // 获取ip
        ServletRequestAttributes request = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        assert request != null;
        String ip = request.getRequest().getRemoteAddr();
        log.info("访问ip：{}", ip);
        String mobile = dto.getMobile();
        List<BlackList> lists = (List<BlackList>) redisTemplate.opsForValue().get(RedisConstants.CACHE_BLACKLIST);
        lists.forEach(black -> {
            if (black.getIp().equals(ip) && black.getPhone().equals(mobile)) {
                throw new BusinessException(YmccSystemError.SHIELD_SEND_CODE);
            }
        });

        // 用于存放验证码
        String code = "";
        // 查询手机号验证码是否已经存在未过期
        final String value = stringRedisTemplate.opsForValue().get(YmccConstants.REGISTER_CODE + dto.getMobile());
        if (value != null) {// 没有过期
            // 获取时间 判断是否频繁操作
            long oldTime = Long.parseLong(value.split(":")[1]);
            if (System.currentTimeMillis() - oldTime <= 1000L * codeProperties.getInterval()) {
                // 一分钟之内不允许频繁操作
                throw new BusinessException(YmccSystemError.FREQUENT_OPERATION);
            } else {
                code = value.split(":")[0];
            }
        } else {
            // 验证码过期 生成新的验证码
            code = RandomUtil.randomNumbers(codeProperties.getLength());
        }
        // 将验证码信息存入数据库
        MessageSms messageSms = getMessageSms(
                YmccConstants.SMS_REGISTER_CONTENT_PREFIX + code + YmccConstants.SMS_REGISTER_CONTENT_SUFFIX, dto.getMobile());
        smsMapper.insert(messageSms);
        // 存入redis
        stringRedisTemplate.opsForValue().set(YmccConstants.REGISTER_CODE + dto.getMobile(), code + ":" + System.currentTimeMillis(), codeProperties.getExpire(), TimeUnit.MINUTES);
        // 发送验证码短信
//        SmsUtils.sendSms(phone, "您的验证码是：" + code + ",请在十分钟之内使用。");
        log.info("=========【源码云课堂】您的验证码是:{}=========", code);
        return JSONResult.success();
    }

    private MessageSms getMessageSms(String content, String phone) {
        final MessageSms messageSms = new MessageSms();
        messageSms.setPhone(phone);
        messageSms.setContent(content);
        messageSms.setTitle(YmccConstants.SMS_REGISTER_TITLE);
        messageSms.setSendTime(new Date());
        // 获取IP
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        assert requestAttributes != null;
        String ipAddress = requestAttributes.getRequest().getRemoteAddr();
        messageSms.setIp(ipAddress);
        return messageSms;
    }

    @Override
    public JSONResult getImageCode(String imageCodeKey) {
        String capStr = null, code = null;
        BufferedImage image = null;

        // 生成验证码
        if ("math".equals(captchaType)) {
            String capText = captchaProducerMath.createText();
            capStr = capText.substring(0, capText.lastIndexOf("@"));
            code = capText.substring(capText.lastIndexOf("@") + 1);
            image = captchaProducerMath.createImage(capStr);
        } else if ("char".equals(captchaType)) {
            capStr = code = captchaProducer.createText();
            image = captchaProducer.createImage(capStr);
        }
        System.out.println(code + "=====================");
        redisCache.setCacheObject(imageCodeKey, code, YmccConstants.CAPTCHA_EXPIRATION, TimeUnit.MINUTES);
        // 转换流信息写出
        FastByteArrayOutputStream os = new FastByteArrayOutputStream();
        try {
            ImageIO.write(image, "jpg", os);
        } catch (IOException e) {
            return JSONResult.error(e.getMessage());
        }
        return JSONResult.success(Base64.encode(os.toByteArray()));
    }
}
